<template>
  <el-dialog v-if="load" :close-on-click-modal="false" title="变更产品信息" v-model="visible" append-to-body :z-index="2000" align-center width="1300px" @close="handleClose">
    <el-form ref="formRef" :disabled="isLook" :model="form" label-position="left">
      <div class="grid grid-cols-4 gap-x-3 mt-2">
        <el-form-item label="变更类型" prop="change_method" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <VSelect v-model="form.change_method" placeholder="请选择" type="demandChange" class="w-full" @change="form.change_reason = null" />
        </el-form-item>
        <el-form-item label="变更原因" prop="change_reason" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <VSelect v-model="form.change_reason" placeholder="请选择" select :options="changeOptions[form.change_method]" class="w-full" />
        </el-form-item>
        <el-form-item label="变更备注" class="col-span-2">
          <VText v-if="isLook" :value="form.change_remark"></VText>
          <el-input v-else v-model="form.change_remark" type="textarea" :rows="1" placeholder="请输入" />
        </el-form-item>
      </div>
      <template v-if="log">
        <div class="mb-3 font-bold">变更前数据</div>
      </template>
      <vxe-table ref="tableRef" :data="form.data" size="small" :loading="loadings.data">
        <vxe-column :min-width="140">
          <template #header>
            <div>sku</div>
          </template>
          <template #default="{ row }">
            <VText title="需求ID" :value="row.sku_no" />
            <VText :value="row.sku">
              <span class='whitespace-nowrap'>{{row.sku}}</span>
              <el-tag v-if="row.is_new === 2" type="success" effect="dark" class='mx-1'>新</el-tag>
              <el-tag v-if="row.is_special_purchase === 2" type="danger" effect="dark">特</el-tag>
            </VText>
            <VText title='供应商编码' :value="row.supplier_code" />
            <VAuth auth="/purchase/demand/change/supplierName">
              <VText title='供应商名称' :value="row.supplier_name" title-position="top" />
            </VAuth>
          </template>
        </vxe-column>
        <vxe-column :min-width="120">
          <template #header>
            <div><span class="text-red-600">*</span> 总需求数量</div>
          </template>
          <template #default="{ row, rowIndex }">
            <div class="flex flex-col gap-1 p-1">
              <template v-if="isLook">
                <div>{{ row.demand_num }}</div>
              </template>
              <template v-else>
                <el-form-item :prop="['data', rowIndex, 'demand_num']" label="" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
                  <el-input-number v-model="row.demand_num" :controls="false" :min="0" :step="1" :precision="0" class="w-full" />
                </el-form-item>
              </template>
            </div>
          </template>
        </vxe-column>
        <vxe-column :min-width="140">
          <template #header>
            <div><span class="text-red-600">*</span> 平台</div>
          </template>
          <template #default="{ row, rowIndex }">
            <div class="flex flex-col gap-1 p-1">
              <el-form-item :prop="['data', rowIndex, 'platform']" label="" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
                <VSelect v-model="row.platform" :options="options.platform" disabled select placeholder="平台" class="w-full" />
              </el-form-item>
            </div>
          </template>
        </vxe-column>
        <vxe-column :min-width="160">
          <template #header>
            <span class="text-red-600">*</span> 国家
            <div><span class="text-red-600">*</span> 需求日期</div>
          </template>
          <template #default="{ row, rowIndex }">
            <div class="flex flex-col gap-1 p-1">
              <template v-if="isLook">
                <VText :value="row.country_name" />
                <VText :value="row.demand_time" />
              </template>
              <template v-else>
                <el-form-item :prop="['data', rowIndex, 'country']" label="" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
                  <VSelect v-model="row.country" placeholder="国家" :options="options.country" select filterable clearable disabled class="w-full"
                    @change="row.destination_warehouse = ''" />
                </el-form-item>
                <el-form-item :prop="['data', rowIndex, 'demand_time']" label="" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
                  <el-date-picker v-model="row.demand_time" type="date" value-format="YYYY-MM-DD" class="w-full" placeholder="需求日期" />
                </el-form-item>
              </template>
            </div>
          </template>
        </vxe-column>
        <vxe-column :min-width="160">
          <template #header>
            <div v-if="form.data && form.data[0] && form.data[0].demand_type === 2">ASIN</div>
            <span class="text-red-600" v-if="form.data && form.data[0] && form.data[0].demand_type !== 2">*</span> 目的仓
            <div><span class="text-red-600">*</span> 预计运输方式</div>
          </template>
          <template #default="{ row, rowIndex }">
            <div class="flex flex-col gap-1 p-1">
              <template v-if="isLook">
                <VText v-if="row.demand_type === 2" :value="row.asin" />
                <VText :value="row.destination_warehouse_name" />
                <VSelect v-model="row.transport_type" placeholder="预计运输方式" :options="options.transport_type" select filterable clearable class="w-full" :disabled="isLook" />
              </template>
              <template v-else>
                <el-input v-if="row.demand_type === 2" v-model="row.asin" placeholder="请输入" class="w-full" />
                <el-form-item :prop="['data', rowIndex, 'destination_warehouse']" label="" :rules="[{ required: row.demand_type !== 2, message: '不能为空', trigger: 'change' }]">
                  <VSelect v-model="row.destination_warehouse" placeholder="目的仓"
                    :options="row.country === 'US' ? options.destination_warehouse : options.plan_destination_warehouse" filterable clearable disabled class="w-full" />
                </el-form-item>
                <el-form-item :prop="['data', rowIndex, 'transport_type']" label="" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
                  <VSelect v-model="row.transport_type" placeholder="预计运输方式" :options="options.transport_type" select filterable clearable disabled class="w-full" />
                </el-form-item>
              </template>
            </div>
          </template>
        </vxe-column>
        <vxe-column :min-width="400">
          <template #header>
            <div><span class="text-red-600">*</span> 负责销售/<span class="text-red-600">*</span> 需求数量/部门</div>
          </template>
          <template #default="{ row, rowIndex }">
            <template v-if="isLook">
              <div class="grid grid-cols-3 border-l border-t dark:border-gray-700">
                <div class="border-b border-r p-1 dark:border-gray-700">负责销售</div>
                <div class="border-b border-r p-1 dark:border-gray-700">需求数量</div>
                <div class="border-b border-r p-1 dark:border-gray-700">部门</div>
                <template v-if="row.detail.length">
                  <template v-for="(d, i) in row.detail" :key="i">
                    <div class="border-b border-r p-1 dark:border-gray-700">
                      <VCascader v-model="d.sale_id" placeholder="负责销售" filterable clearable disabled />
                    </div>
                    <div class="border-b border-r p-1 dark:border-gray-700">{{ d.demand_num }}</div>
                    <div class="border-b border-r p-1 dark:border-gray-700">
                      <VCascader v-model="d.department_id" type="1" placeholder="负责销售" filterable clearable disabled />
                    </div>
                  </template>
                </template>
                <div v-else class="border-b border-r p-1 dark:border-gray-700 text-center col-span-3 text-gray-500">暂无数据</div>
              </div>
            </template>
            <template v-else>
              <div v-for="(da, idx) in row.detail" :key="idx" class="grid gap-1 p-1 mb-3" style="grid-template-columns: repeat(9, minmax(0, 1fr))">
                <el-form-item :prop="['data', rowIndex, 'detail', idx, 'sale_id']" label="" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]"
                  class="m-0 col-span-3">
                  <VCascader v-model="da.sale_id" placeholder="负责销售" filterable clearable class="w-full" @change="val => saleChange(da, val)" />
                </el-form-item>
                <el-form-item :prop="['data', rowIndex, 'detail', idx, 'demand_num']" label="" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]"
                  class="m-0 col-span-2">
                  <el-input-number v-model="da.demand_num" :controls="false" :min="0" :step="1" :precision="0" placeholder="需求数量" />
                </el-form-item>
                <el-input :value="da.department_name" placeholder="部门" disabled class="col-span-3" />
                <el-button v-if="idx" link type="primary" @click="row.detail.splice(idx, 1)">移除</el-button>
                <el-button v-else link type="primary" @click="row.detail.push({ sale_id: '', department_id: '' })">添加</el-button>
              </div>
            </template>
          </template>
        </vxe-column>
        <vxe-column :min-width="140">
          <template #header>
            备料计划数据
          </template>
          <template #default="{ row }">
            <template v-if="row.plan.length">
              <div v-for="(d, i) in row.plan" :key="i" class="flex flex-col gap-1 p-1">
                <div>{{ d.plan_no }}</div>
                <div>下单数量:{{ d.demand_num }}</div>
              </div>
            </template>
            <div v-else>-</div>
            <el-button v-if="!isLook" link type="primary" @click="() => editNumRef.open(Object.assign(row, {demand_type: row.demand_type, sale_id: row.detail.map(d => d.sale_id)}))">修改</el-button>
          </template>
        </vxe-column>
        <template v-if="!log">
          <vxe-column title="变更备注" min-width="140">
            <template #default="{ row }">
              <el-input v-model="row.detail_remark" placeholder="备注" type="textarea" :autosize="{ minRows: 2, maxRows: 5 }" :maxlength="300" />
            </template>
          </vxe-column>
        </template>
        <vxe-column title="操作" fixed="right" :width="70">
          <template #default="{ rowIndex }">
            <el-button v-if="form.data.length > 1" link type="primary" @click="form.data.splice(rowIndex, 1)">移除</el-button>
          </template>
        </vxe-column>
      </vxe-table>
    </el-form>
    <el-form ref="formChangeRef" :disabled="isLook" :model="form">
      <template v-if="log && form.changeData && form.changeData.length">
        <div class="mt-5 mb-3 font-bold">变更后数据</div>
        <div>
          <vxe-table ref="tableRef" :data="form.changeData" size="small">
            <vxe-column :min-width="140">
              <template #header>
                <div>sku</div>
              </template>
              <template #default="{ row }">
                <VText :value="row.sku">
                  {{ row.sku }}
                  <el-tag v-if="row.is_new === 2" type="success" effect="dark" class='mx-1'>新</el-tag>
                  <el-tag v-if="row.is_special_purchase === 2" type="danger" effect="dark">特</el-tag>
                </VText>
                <VText title='供应商编码' :value="row.supplier_code" />
                <VAuth auth="/purchase/demand/change/supplierName">
                  <VText title='供应商名称' :value="row.supplier_name" title-position="top" />
                </VAuth>
              </template>
            </vxe-column>
            <vxe-column :min-width="120">
              <template #header>
                <div><span class="text-red-600">*</span> 总需求数量</div>
              </template>
              <template #default="{ row, rowIndex }">
                <div class="flex flex-col gap-1 p-1">
                  <template v-if="isLook">
                    <div>{{ row.demand_num }}</div>
                  </template>
                  <template v-else>
                    <el-form-item :prop="['changeData', rowIndex, 'demand_num']" label="" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
                      <el-input-number v-model="row.demand_num" :controls="false" :min="0" :step="1" :precision="0" class="w-full" />
                    </el-form-item>
                  </template>
                </div>
              </template>
            </vxe-column>
            <vxe-column :min-width="140">
              <template #header>
                <div><span class="text-red-600">*</span> 平台</div>
              </template>
              <template #default="{ row, rowIndex }">
                <div class="flex flex-col gap-1 p-1">
                  <el-form-item :prop="['data', rowIndex, 'platform']" label="" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
                    <VSelect v-model="row.platform" :options="options.platform" disabled select placeholder="平台" class="w-full" />
                  </el-form-item>
                </div>
              </template>
            </vxe-column>
            <vxe-column :min-width="160">
              <template #header>
                <span class="text-red-600">*</span> 国家
                <div><span class="text-red-600">*</span> 需求日期</div>
              </template>
              <template #default="{ row, rowIndex }">
                <div class="flex flex-col gap-1 p-1">
                  <template v-if="isLook">
                    <VText :value="row.country_name" />
                    <VText :value="row.demand_time" />
                  </template>
                  <template v-else>
                    <el-form-item :prop="['changeData', rowIndex, 'country']" label="" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
                      <VSelect v-model="row.country" placeholder="国家" select :options="options.country" filterable clearable disabled class="w-full"
                        @change="row.destination_warehouse = ''" />
                    </el-form-item>
                    <el-form-item :prop="['changeData', rowIndex, 'demand_time']" label="" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
                      <el-date-picker v-model="row.demand_time" type="date" value-format="YYYY-MM-DD" class="w-full" placeholder="需求日期" />
                    </el-form-item>
                  </template>
                </div>
              </template>
            </vxe-column>
            <vxe-column :min-width="160">
              <template #header>
                <div v-if="form.changeData[0].demand_type === 2">ASIN</div>
                <span class="text-red-600">*</span> 目的仓
                <div><span class="text-red-600">*</span> 预计运输方式</div>
              </template>
              <template #default="{ row, rowIndex }">
                <div class="flex flex-col gap-1 p-1">
                  <template v-if="isLook">
                    <VText v-if="form.changeData[0].demand_type === 2" :value="row.asin" />
                    <VText :value="row.destination_warehouse_name" />
                    <VSelect v-model="row.transport_type" placeholder="预计运输方式" :options="options.transport_type" select filterable clearable class="w-full" :disabled="isLook" />
                  </template>
                  <template v-else>
                    <el-input v-if="row.demand_type === 2" v-model="row.asin" placeholder="请输入" class="w-full" />
                    <el-form-item :prop="['changeData', rowIndex, 'destination_warehouse']" label="" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
                      <VSelect v-model="row.destination_warehouse" placeholder="目的仓"
                        :options="row.country === 'US' ? options.destination_warehouse : options.plan_destination_warehouse" filterable clearable disabled class="w-full" />
                    </el-form-item>
                    <el-form-item :prop="['changeData', rowIndex, 'transport_type']" label="" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
                      <VSelect v-model="row.transport_type" placeholder="预计运输方式" :options="options.transport_type" select filterable clearable disabled class="w-full" />
                    </el-form-item>
                  </template>
                </div>
              </template>
            </vxe-column>
            <vxe-column :min-width="400">
              <template #header>
                <div><span class="text-red-600">*</span> 负责销售/<span class="text-red-600">*</span> 需求数量/部门</div>
              </template>
              <template #default="{ row, rowIndex }">
                <template v-if="isLook">
                  <div class="grid grid-cols-3 border-l border-t dark:border-gray-700">
                    <div class="border-b border-r p-1 dark:border-gray-700">负责销售</div>
                    <div class="border-b border-r p-1 dark:border-gray-700">需求数量</div>
                    <div class="border-b border-r p-1 dark:border-gray-700">部门</div>
                    <template v-if="row.detail.length">
                      <template v-for="(d, i) in row.detail" :key="i">
                        <div class="border-b border-r p-1 dark:border-gray-700">
                          <VCascader v-model="d.sale_id" placeholder="负责销售" filterable clearable disabled />
                        </div>
                        <div class="border-b border-r p-1 dark:border-gray-700">{{ d.demand_num }}</div>
                        <div class="border-b border-r p-1 dark:border-gray-700">
                          <VCascader v-model="d.department_id" type="1" placeholder="负责销售" filterable clearable disabled />
                        </div>
                      </template>
                    </template>
                    <div v-else class="border-b border-r p-1 dark:border-gray-700 text-center col-span-3 text-gray-500">暂无数据</div>
                  </div>
                </template>
                <template v-else>
                  <div v-for="(da, idx) in row.detail" :key="idx" class="grid gap-1 p-1 mb-3" style="grid-template-columns: repeat(9, minmax(0, 1fr))">
                    <el-form-item :prop="['changeData', rowIndex, 'detail', idx, 'sale_id']" label="" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]"
                      class="m-0 col-span-3">
                      <VCascader v-model="da.sale_id" placeholder="负责销售" filterable clearable class="w-full" @change="val => saleChange(da, val)" />
                    </el-form-item>
                    <el-form-item :prop="['changeData', rowIndex, 'detail', idx, 'demand_num']" label="" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]"
                      class="m-0 col-span-2">
                      <el-input-number v-model="da.demand_num" :controls="false" :min="0" :step="1" :precision="0" placeholder="需求数量" />
                    </el-form-item>
                    <el-input :value="da.department_name" placeholder="部门" disabled class="col-span-3" />
                    <el-button v-if="idx" link type="primary" @click="row.detail.splice(idx, 1)">移除</el-button>
                    <el-button v-else link type="primary" @click="row.detail.push({ sale_id: '', department_id: '' })">添加</el-button>
                  </div>
                </template>
              </template>
            </vxe-column>
            <vxe-column :min-width="140">
              <template #header>
                备料计划数据
              </template>
              <template #default="{ row }">
                <template v-if="row.plan.length">
                  <div v-for="(d, i) in row.plan" :key="i" class="flex flex-col gap-1 p-1">
                    <div>{{ d.plan_no }}</div>
                    <div>下单数量:{{ d.demand_num }}</div>
                  </div>
                </template>
                <div v-else>-</div>
                <el-button v-if="!isLook" link type="primary" @click="() => editNumRef.open(Object.assign(row, {demand_type: row.demand_type, sale_id: row.detail.map(d => d.sale_id)}))">修改</el-button>
              </template>
            </vxe-column>
            <vxe-column title="变更备注" min-width="140">
              <template #default="{ row }">
                <el-input v-model="row.detail_remark" placeholder="备注" type="textarea" :autosize="{ minRows: 2, maxRows: 5 }" :maxlength="300" />
              </template>
            </vxe-column>
          </vxe-table>
        </div>
      </template>
    </el-form>
    <EditNum ref="editNumRef" />
    <template v-if="!isLook && !log" #footer>
      <el-button @click="close">关 闭</el-button>
      <el-button type="primary" :loading="loadings['submit' + 2]" @click="submit(2)">确 定</el-button>
      <el-button type="primary" :loading="loadings['submit' + 1]" @click="submit(1)">提 交</el-button>
    </template>
    <template v-if="!isLook && (log && form.changeData && form.changeData.length)" #footer>
      <el-button @click="close">关 闭</el-button>
      <el-button type="primary" :loading="loadings['changeSubmit' + 2]" @click="changeSubmit(2)">确 定</el-button>
      <el-button type="primary" :loading="loadings['changeSubmit' + 1]" @click="changeSubmit(1)">提 交</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import XEUtils from 'xe-utils'
import EditNum from './EditNum'
import api from './api'
import { platforms } from '@/api/public'
import { ElMessage } from 'element-plus';
import { getDepartment } from '@/api/public'
import { reactive } from 'vue';

const props = defineProps({
  options: { type: Object, default: () => ({}) },
  log: Boolean,
  isChange: Boolean,
})

const load = ref(false)
const visible = ref(false)
const isLook = ref(false)
const loadings = reactive({})
let form = reactive({ change_method: null, change_reason: null, change_remark: '', data: [], changeData: [] })
const formRef = ref()
const formChangeRef = ref()
const editNumRef = ref()

const platformsOptions = ref([])
const emit = defineEmits(['close', 'success'])
platforms().then(res => {
  platformsOptions.value = res
})
const changeOptions = ref([])
api.getChangeOption().then(res => {
  changeOptions.value = res.data.reduce((acc, cur) => {
    acc[cur.value] = cur.sub_option
    return acc
  }, {})
})

const saleChange = (da, { value }) => {
  getDepartment({ select_user_id: value }).then(res => {
    da.department_id = res.data.department_id
    da.department_name = res.data.department_name
  })
}

// 打开弹窗
const open = async (params, change) => {
  if (!load.value) {
    load.value = true
    await 1
  }
  form = reactive({ change_method: null, change_reason: null, change_remark: '', data: [], changeData: [] })
  visible.value = true
  formRef?.value?.resetFields()
  if (Array.isArray(params)) {
    form.data = params
  } else if (props.log && change) {
    isLook.value = change.look
    form = reactive(change)
  } else {
    loadings.data = true
    const res = await api.detail(params)
    let table = []
    for(let key in res.data){
      table.push(res.data[key])
    }
    form.data = table
    loadings.data = false
  }
}
// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
}

// 跟踪单提交
const submit = async (is_submit) => {
  const validator = await formRef?.value?.validate()
  if (!validator) return
  const submitData = {
    ...form,
    sku: form.data,
    is_submit,
  }
  loadings['submit' + is_submit] = true
  api.change(submitData).then(res => {
    ElMessage.success('提交成功')
    emit('success')
    close()
  }).finally(() => {
    loadings['submit' + is_submit] = false
  })
}
// 变更单提交
const changeSubmit = async (is_submit) => {
  const validator = await formRef?.value?.validate()
  const validatorChange = await formChangeRef?.value?.validate()
  if (!validator || !validatorChange) return
  const submitData = {
    ...form,
    pdc_id: form.changeData[0].pdc_id,
    sku: form.changeData[0],
    is_submit
  }
  loadings['changeSubmit' + is_submit] = true
  api.edit(submitData).then(res => {
    ElMessage.success('提交成功')
    emit('success')
    close()
  }).finally(() => {
    loadings['changeSubmit' + is_submit] = false
  })
}

defineExpose({ open, close })
</script>